﻿import file_default_icon from '@/assets/imgs/uploadIcon/file_default_icon.png';
import file_folder_icon from '@/assets/imgs/uploadIcon/file_folder_icon.png';
import file_mp3_icon from '@/assets/imgs/uploadIcon/file_mp3_icon.png';
import file_mp4_icon from '@/assets/imgs/uploadIcon/file_mp4_icon.png';
import file_pdf_icon from '@/assets/imgs/uploadIcon/file_pdf_icon.png';
import file_pic_icon from '@/assets/imgs/uploadIcon/file_pic_icon.png';
import file_ppt_icon from '@/assets/imgs/uploadIcon/file_ppt_icon.png';
import file_txt_icon from '@/assets/imgs/uploadIcon/file_txt_icon.png';
import file_word_icon from '@/assets/imgs/uploadIcon/file_word_icon.png';
import file_xls_icon from '@/assets/imgs/uploadIcon/file_xls_icon.png';
import file_zip_icon from '@/assets/imgs/uploadIcon/file_zip_icon.png';

export const typeList = {
    zipArray: ['rar', 'zip', '7z'],
    pictureArray: ['jpg', 'jpeg', 'png', 'gif', 'psd', 'bmp', 'dxf', 'svg', 'xbm', 'art'],
    videoArray: ['avi', 'wmv', 'mpeg', 'mp4', 'm4v', 'mov', 'asf', 'flv', 'f4v', 'rmvb', 'rm', '3gp', 'vob'],
    voiceArray: ['mp3', 'wav', 'wma', 'm4a', 'flac', 'ape', 'wv'],
    wordArray: ['doc', 'docx', 'docm', 'dotx', 'dot', 'dotm'],
    excelArray: ['xlsx', 'xlsm', 'xls', 'xlsb', 'xltx', 'xlt', 'xltm'],
    pptArray: ['pptx', 'ppt', 'pptm', 'ppsx', 'ppsm', 'pps', 'ppa', 'pot', 'potm'],
    pdfArray: ['pdf'],
    txtArray: ['txt', 'rtf', 'xml', 'xps', 'log'],
};

export const extractFileName = (str: string) => {
    const regex = /'fileName':\s*'([^']*)'/;
    const match = str.match(regex);
    return match ? match[1] : null;
};

export const getFileTypeIcon = (filePath: string) => {
    if (!filePath) return;
    let path = '';
    let fileWorkArr = filePath.split('.');
    if (fileWorkArr.length > 0) {
        let type = fileWorkArr[fileWorkArr.length - 1];
        if (typeList.pictureArray.includes(type as string)) {
            path = file_pic_icon;
        } else if (typeList.zipArray.includes(type as string)) {
            path = file_zip_icon;
        } else if (typeList.videoArray.includes(type as string)) {
            path = file_mp4_icon;
        } else if (typeList.wordArray.includes(type as string)) {
            path = file_word_icon;
        } else if (typeList.excelArray.includes(type as string)) {
            path = file_xls_icon;
        } else if (typeList.pptArray.includes(type as string)) {
            path = file_ppt_icon;
        } else if (typeList.pdfArray.includes(type as string)) {
            path = file_pdf_icon;
        } else if (typeList.txtArray.includes(type as string)) {
            // path = asset('uploadIcon/file_txt_icon.png');
            path = file_txt_icon;
        } else if (typeList.voiceArray.includes(type as string)) {
            path = file_mp3_icon;
        } else {
            path = file_default_icon;
        }
    }
    return path;
};
export const getFileIconByGroupNotice = (fileName: string) => {
    if (!fileName) return '';
    let fileWorkArr = fileName.split('.');
    if (fileWorkArr.length > 0) {
        let type: any = fileWorkArr[fileWorkArr.length - 1];
        return getFileTypeIcon(type);
    }
};

export const errorTips = (message: string) => {
    showToast({
        message,
        position: 'top',
    });
};

export const successTips = (message: string) => {
    showToast({
        message,
        position: 'top',
    });
};

export const warningTips = (message: string) => {
    showToast({
        message,
        position: 'top',
    });
};

/**
 * 存储sessionStorage
 */
export const setStore = (name: string, content: any) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);
    }
    window.sessionStorage.setItem(name, content);
};

/**
 * 获取sessionStorage
 */
export const getStore = (name: string) => {
    if (!name) return;
    let content = window.sessionStorage.getItem(name);
    if (!content) return '';
    if (content.indexOf('{') >= 0 || content.indexOf('[') >= 0) {
        return JSON.parse(content);
    } else {
        return content;
    }
};

/**
 * 删除sessionStorage
 */
export const removeStore = (name: string) => {
    if (!name) return;
    window.sessionStorage.removeItem(name);
};

/**
 * 时间戳格式化
 */
export const getDateTime = function (timestamp?: string) {
    let t = null;
    // 不传值，则获取当前时间
    if (timestamp === undefined) {
        t = new Date();
    } else if (timestamp) {
        t = new Date(parseInt(timestamp));
    }

    if (t) {
        let n: string = t.getFullYear() + '';
        let a: string = t.getMonth() + 1 + '';
        let r: string = t.getDate() + '';
        let o: string = t.getHours() + '';
        let i: string = t.getMinutes() + '';
        let s: string = t.getSeconds() + '';

        parseInt(a) >= 10 || (a = '0' + a),
            parseInt(r) >= 10 || (r = '0' + r),
            parseInt(o) >= 10 || (o = '0' + o),
            parseInt(i) >= 10 || (i = '0' + i),
            parseInt(s) >= 10 || (s = '0' + s);

        return [
            n, // yy 0
            a, // mm 1
            r, // dd 2
            n + '-' + a, // yy-mm 3
            a + '/' + r, // mm/dd 4
            o + ':' + i + ':' + s, // hh:mm:ss 5
            n + '-' + a + '-' + r + ' ' + o + ':' + i + ':' + s, // yy-mm-dd hh:mm::ss 6
            a + '-' + r + ' ' + o + ':' + i + ':' + s, // mm-dd hh:mm::ss 7
            n + '-' + a + '-' + r, // yy-mm-dd 8
            n + a + r, // yymmdd 9
            n + a, //yymm 10
            n + '-' + a + '-' + r + ' ' + o + ':' + i, // yy-mm-dd hh:mm 11
        ];
    } else {
        return ['--', '--', '--', '--', '--', '--', '--', '--', '--'];
    }
};

/**
 * 日期转时间戳
 */
export const getTimestamp = (e: string) => {
    var t;
    if (e) {
        e = e.replace(/-/g, '/');
        t = new Date(e);
    } else t = new Date();
    return t.getTime().toString();
};

/**
 * 去抖动函数
 */
export const debounce = <T extends (...args: any[]) => any>(
    func: T,
    wait: number,
    immediate = false
): ((...args: Parameters<T>) => ReturnType<T> | undefined) => {
    let timeout: ReturnType<typeof setTimeout> | null = null;

    return function (this: any, ...args: Parameters<T>): ReturnType<T> | undefined {
        const context = this;
        const later = () => {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };

        const callNow = immediate && !timeout;

        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(later, wait);

        if (callNow) return func.apply(context, args);
    };
};

// 节流
export const throttle = <T extends (...args: any[]) => any>(
    func: T,
    limit: number
): ((...args: Parameters<T>) => ReturnType<T> | undefined) => {
    let lastFunc: ReturnType<typeof setTimeout> | null = null;
    let lastRan: number | null = null;

    return function (this: any, ...args: Parameters<T>): ReturnType<T> | any {
        const context = this;

        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            if (lastFunc) clearTimeout(lastFunc);

            lastFunc = setTimeout(() => {
                if (Date.now() - lastRan! >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan!)) as ReturnType<typeof setTimeout>;
        }
    };
};

/**
 * 获取浏览器URL中的查询参数
 * @param url 可选，要解析的URL，默认为当前页面URL
 * @returns 返回解析后的查询参数对象
 */
export function getUrlParams(url?: string): Record<string, string> {
    const targetUrl = url || window.location.href;
    const params: Record<string, string> = {};

    // 处理标准URL参数（如：http://example.com?a=1&b=2）
    const standardQueryIndex = targetUrl.indexOf('?');
    if (standardQueryIndex !== -1) {
        const queryString = targetUrl.slice(standardQueryIndex + 1);
        const hashIndex = queryString.indexOf('#');
        const cleanQuery = hashIndex !== -1 ? queryString.slice(0, hashIndex) : queryString;

        cleanQuery.split('&').forEach(param => {
            if (param) {
                const [key, value] = param.split('=');
                if (key) {
                    params[key] = value ? encodeURIComponent(value) : '';
                }
            }
        });
    }

    // 处理哈希路由中的参数（如：http://example.com/#/page?a=1&b=2）
    const hashIndex = targetUrl.indexOf('#');
    if (hashIndex !== -1) {
        const hashPart = targetUrl.slice(hashIndex + 1);
        const hashQueryIndex = hashPart.indexOf('?');

        if (hashQueryIndex !== -1) {
            const hashQueryString = hashPart.slice(hashQueryIndex + 1);

            hashQueryString.split('&').forEach(param => {
                if (param) {
                    const [key, value] = param.split('=');
                    if (key) {
                        // 优先使用哈希中的参数（覆盖标准URL中的同名参数）
                        params[key] = value ? encodeURIComponent(value) : '';
                    }
                }
            });
        }
    }

    return params;
}

export const isJsonStr = (str: string) => {
    try {
        let obj = JSON.parse(str);
        return typeof obj == 'object' && obj;
    } catch (e) {
        return false;
    }
};

/**
 * 加载图片，兼容重定向，支持失败重试，返回图片对象和最终地址
 * @param {string} url - 原始图片地址（可能重定向）
 * @param {number} [maxRetries=3] - 最大重试次数，默认 3
 * @param {number} [retryDelay=1000] - 每次重试间隔（毫秒），默认 1000ms
 * @returns {Promise<{ img: HTMLImageElement, finalUrl: string }>} 返回图片对象和它最终加载的地址
 */
export function loadImageWithRedirectSupportAndRetry(url: string, maxRetries = 3, retryDelay = 300) {
    return new Promise((resolve, reject) => {
        let retryCount = 0;

        const tryLoad = async () => {
            try {
                console.log(`[尝试加载] 原始地址（第 ${retryCount + 1} 次）:`, url);

                // 1. 先通过 fetch 获取重定向后的最终地址
                const response = await fetch(url, {
                    method: 'GET',
                    redirect: 'follow', // 自动跟随重定向
                });

                // 2. 拿到最终跳转后的地址
                const finalUrl = response.url;
                console.log(`[解析重定向] 最终图片地址:`, finalUrl);

                // 3. 用最终地址加载图片
                const img = new Image();

                img.onload = () => {
                    console.log('✅ 图片加载成功（最终地址）:', finalUrl);
                    resolve(finalUrl); // 成功返回图片对象 + 最终地址
                };

                img.onerror = () => {
                    retryCount++;
                    console.warn(`⚠️ 图片加载失败（最终地址: ${finalUrl}），第 ${retryCount} 次重试`);

                    if (retryCount < maxRetries) {
                        setTimeout(tryLoad, retryDelay);
                    } else {
                        const errorMsg = `❌ 图片加载失败，重试 ${maxRetries} 次后仍无法加载。最终地址：${finalUrl}`;
                        console.error(errorMsg);
                        reject(new Error(errorMsg));
                    }
                };

                // 使用最终地址加载图片
                img.src = finalUrl;
            } catch (error) {
                retryCount++;
                console.warn(`⚠️ 网络请求失败（原始地址: ${url}），第 ${retryCount} 次重试。错误：`, error);

                if (retryCount < maxRetries) {
                    setTimeout(tryLoad, retryDelay);
                } else {
                    const errorMsg = `❌ 无法获取或加载图片，重试 ${maxRetries} 次后失败。原始地址：${url}`;
                    console.error(errorMsg);
                    reject(new Error(errorMsg));
                }
            }
        };

        // 开始第一次尝试
        tryLoad();
    });
}
